<template>
  <div>
    <mbx lenev="商品管理" lenev1="商品列表" lenev2="添加商品">
      <template v-slot:dao>
        <div>
             <el-breadcrumb-item>添加商品</el-breadcrumb-item>
        </div>
      </template>
    </mbx>
    <el-card style="margin-top: 20px">
      <el-alert title="添加商品信息" type="info" center show-icon> </el-alert>

      <el-steps
        :active="buzhou * 1"
        finish-status="success"
        align-center
        style="margin-top: 20px"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-form :model="spfrom" :rules="goodrules">
        <el-tabs
          v-model="buzhou"
          :before-leave="bfleave"
          @tab-click="goodcan"
          tab-position="left"
          style="margin-top: 25px"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="spfrom.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="spfrom.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="spfrom.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="spfrom.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <el-cascader v-model="spcheck" :options="spshuju" :props="sppz">
              </el-cascader>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyarr"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="item1"
                  v-for="(item1, index) in item.attr_vals"
                  :key="index"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyarr"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-form-item>
              <el-upload
                class="upload-demo"
                action="http://www.ysqorz.top:8888/api/private/v1/upload"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-success="handleSucc"
                :headers="headers"
                list-type="picture"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过500kb
                </div>
              </el-upload>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <el-form-item>
               <quill-editor v-model="spfrom.goods_introduce"/>
               <el-button type="primary" style="margin-top:15px" @click="addgood">添加商品</el-button>
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import _ from "lodash"
export default {
  data() {
    return {
      headers:{
        Authorization:sessionStorage.getItem('token')
      },
      // 三级分类渲染规则
      sppz: {
        expandTrigger: "hover",
        label: "cat_name",
        children: "children",
        value: "cat_id",
      }, 
      // 添加商品的所有数据
      spfrom: {
        goods_cat:'',
        goods_name: "",
        goods_price: "0",
        goods_weight: "0",
        goods_number: "0",
        goods_introduce:'',
        pics:[],
        attrs:[]
      }, 
      spcheck: [], //三级分类选中
      spshuju: [], //商品数据
      buzhou: "0", //步骤条关联
      goodrules: {
        goods_name: [{ required: true, message: "请输入商品信息", trigger: "blur" }],
        goods_price: [{ required: true, message: "请输入商品价格", trigger: "blur" }],
        goods_weight: [{ required: true, message: "请输入商品重量", trigger: "blur" }],
        goods_number: [{ required: true, message: "请输入商品数量", trigger: "blur" }],
      },
      manyarr: [],//动态参数
      onlyarr: [],//静态参数
    };
  },
  created() {
    this.getgoods();
  },
  methods: {
   async addgood(){
      // /处理分类数组，转换为以逗号分隔的字符串
       this.spfrom.goods_cat=this.spcheck.join(',')
       //2.将动态参数和静态属性合并，赋值给attrs
      //第一步：使用lodash中的cloneDeep实现深拷贝，解决对象之间相互影响的问题
      let manynewarr=_.cloneDeep(this.manyarr)
      // 使用数组map方法实现获取数组其中一些数据格式动态参数需要转换为字符串
      //return的格式与添加接口一样
      manynewarr=manynewarr.map(item=>{
         return {
              "attr_id":item.attr_id,
               "attr_value":item.attr_vals.join(',')
         }
       })
        // 静态参数直接就是字符串
      let onlynewarr=_.cloneDeep(this.onlyarr)
      onlynewarr=onlynewarr.map(item=>{
         return {
              "attr_id":item.attr_id,
               "attr_value":item.attr_vals
         }
       })
      //  console.log(this.manyarr)
      //     console.log(manynewarr)
      //  console.log(this.onlyarr)
      //  console.log(onlynewarr) 
      //  参数数组合并
       this.spfrom.attrs=[...manynewarr,...onlynewarr]
       console.log(this.spfrom.attrs)
      //  深拷贝需要传递的所有参数
       let spfromadd=_.clone(this.spfrom)
       const res=await this.$API.addgoods(spfromadd)
       console.log(res)
       this.$router.push('/goods')
    },
    handlePreview(){
      
    },
    // 图片点击删除后的函数
    handleRemove(aa){
         console.log(aa)
        //  获取删除图片路径
         let tu=aa.response.data.tmp_path
        //  根据删除图片路径查找数组里相同路径下标
         const index=this.spfrom.pics.findIndex(item=>{
           return item.pic===tu
         })
         this.spfrom.pics.splice(index,1)
        console.log(this.spfrom.pics)
    },
    // 图片上传成功后的函数
    handleSucc(res){
      console.log(res)
      // 解构图片路径 对象形式 将结构出来的路径起个属性名pic与接口数据格式一致
      let path={pic:res.data.tmp_path}
      this.spfrom.pics.push(path)
    },
    // 设置点击左导航栏点击之前事件，判断上一级是不是第一级和选没选完三级分类
    bfleave(next, top) {
      console.log(next, top);
      if (top === "0" && this.spcheck.length < 3) {
        this.$message({
          message: "请选择3级分类",
          type: "error",
        });
        return false;
      }
    },
    async getgoods() {
      // 获取分类数据
      const res = await this.$API.Splist();
      this.spshuju = res;
    },
    async goodcan() {
      // 点击左侧导航栏获取分类参数动态参数和静态参数
      if (this.buzhou === "1") {
        const res = await this.$API.Flcs(this.flid);
        res.forEach((item) => {
          //将res里的attr_vals转换为数组
          item.attr_vals = item.attr_vals.split(",");
        });
        this.manyarr = res;
        console.log(this.manyarr);
      } else if (this.buzhou === "2") {
        // 静态参数本来就是数组形式
        const res = await this.$API.Flcs(this.flid, "only");
        console.log(res);
        this.onlyarr = res;
      }
    },
  },
  mounted() {},

  computed: {
    // 获取第三级分类最后一级id 用来获取分类参数
    flid() {
      return this.spcheck[this.spcheck.length - 1];
    },
  },

  watch: {
    cart: {
      handler(newValue) {},
      deep: true,

      immediate: true,
    },
  },
};
</script>

<style scoped lang="scss">
.el-input {
  margin-top: 10px;
}
::v-deep .el-form-item__label {
  text-align: left;
  width: 100%;
}
::v-deep.el-checkbox {
  border: 1px solid blue;
  border-radius: 5px;
  padding: 0 5px;
  margin: 5px 8px;
}
::v-deep .ql-container {
  height: 300px;
}
</style>
